﻿using PagedList;
using SIG.DAL.Dapper.Repositories;
using SIG.Infrastructure.Configs;
using SIG.Model;
using SIG.Service;
using SIG.ViewModel;
using SIG.ViewModel.Admin;
using SIG.WebMVC.Filters;
using System;
using System.Web.Mvc;

namespace SIG.WebMVC.Areas.Admin.Controllers
{
    [SIGAuth]
    public class LogsController : BaseController
    {
        LogRepository _logRepository;   
        public LogsController()
        {
            _logRepository = new LogRepository();
        }

      
        public ActionResult Index(int? page, DateTime? startDate, DateTime? expireDate, string level)
        {
            var logSearchVM = new LogSearchVM()
            {
                StartDate = startDate,
                ExpireDate = expireDate,
                Level = level,

                PageIndex = (page ?? 1),
                PageSize = SettingsManager.Log.PageSize
            };
            int totalCount;
            logSearchVM.Logs = _logRepository.GetListPagedItems(logSearchVM.PageIndex, logSearchVM.PageSize, startDate, 
                expireDate, level,out totalCount);
            logSearchVM.TotalUserCount = totalCount;

            var logsAsIPagedList = new StaticPagedList<SIG.DAL.Dapper.Model.Log>(logSearchVM.Logs, logSearchVM.PageIndex, logSearchVM.PageSize, logSearchVM.TotalUserCount);
            ViewBag.OnePageOfLogs = logsAsIPagedList;

            return View(logSearchVM);

        }


    
        [HttpPost]  
        public JsonResult Delete(string id)
        {
            if (id == "all")
            {
                int count = _logRepository.RemoveAll();
                if (count > 0)
                {
                    AR.SetSuccess("已清空所有日志");
                    return Json(AR, JsonRequestBehavior.DenyGet);
                }                   
            }
            else
            {
                
                int logId;
                Int32.TryParse(id, out logId);               
                _logRepository.Delete(logId);

                AR.SetSuccess("已成功删除日志");
                return Json(AR, JsonRequestBehavior.DenyGet);            
               
            }

            AR.Setfailure("删除日志失败");
            return Json(AR, JsonRequestBehavior.DenyGet);          
        }
            
    }
}